import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int nearestExit(char[][] maze, int[] entrance) {
        int[] dx = {1,-1,0,0};
        int[] dy = {0,0,1,-1};
        int m = maze.length, n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(entrance);
        visited[entrance[0]][entrance[1]] = true; // 标记已经访问过了
        int ret = 0; // 记录层数
        // 从当前位置开始BFS
        while (!queue.isEmpty()) {
            ret++;
            int size = queue.size();
            // 确保每一层都走完了
            while (size-- != 0) {
                int[] arr = queue.poll();
                for (int k = 0; k < 4; k++) {
                    int sr = arr[0] + dx[k], sc = arr[1] + dy[k];
                    if (sr >= 0 && sr < m && sc >= 0 && sc < n 
                        && maze[sr][sc] == '.' && !visited[sr][sc]) {
                        // 判断是否走到出口了
                        if (sr == 0 || sr == m-1 || sc == 0 || sc == n-1) {
                            return ret;
                        }
                        queue.offer(new int[]{sr, sc});
                        visited[sr][sc] = true;
                    }
                }
            }
        }
        return -1;
    }
}